#!/usr/bin/perl


# Program to discover filename -> Movietitle
# create for a directory for scrapers
# i.e. poe-ca.avi -> Captain.America.BDRip.German.2011 
#
# http://ajax.googleapis.com/ajax/services/search/web?q=prv-puncture-720p&v=1.0

use strict;
use warnings;

use Getopt::Long;
use File::Basename;
use LWP::Simple;
use JSON::XS;
my $json = JSON::XS->new();

use Data::Dumper;
sub dumper { print '<pre>'.Dumper(@_).'</pre>'; }

my( $targetDir, $console, $test ) = (undef, 0, 0);
my @suffixlist = qw/.avi .mkv .mpg/;


GetOptions(
  'TARGET|t=s' => \$targetDir,
  'CONSOLE|c' => \$console,
  'TEST|u' => \$test,
);

die 'Please set Parameters --target and ~/tmp/*!'
   unless($targetDir or scalar @ARGV);

my @files = @ARGV;

foreach my $file (@files){
   # Get all useful Data from this File (Date, Size, etc)
   my $fileData = getFileData($file) 
      or warn "Problem to get Data from File";

   # Call Webservice from isohunt
   my $movieData = getMovieData($fileData) or next;

   # Create Directorys and save Info Files
   my $result = saveInformationInTarget($movieData, $fileData, $targetDir)
      or die "Problem to save Data";
}


sub getFileData {
   my $file = shift or die "No File in getFileData!";
   my($name,$path,$suffix) = fileparse($file, qr/\.[^.]*/);
   return if(! $name);
   printf "\tGet data from File %s%s ... \n", $name, $suffix;

   return {
      moviename => (split(' ', $name))[0],
      filename => sprintf('%s%s', $name, $suffix),
      filesize => -s $file,
      file => $file,
   };
}

sub getMovieData {
   my $data = shift or die "No Data in getMovieData!";
   my $userinput = shift || '';

   my $searchString = $userinput || $data->{moviename};

   printf "\tSearch for '%s':\n", $searchString;

   my $url = sprintf('http://ajax.googleapis.com/ajax/services/search/web?q=%s+site:hd-area.org&v=1.0&rsz=large&key=ABQIAAAA7RCfQlffeyHeqfKc9tfnYxQW5W6ejMvDaoSNDmMS1Qoy5rN5hxQ8xpJck7Hqcr5MU3ao9OZGkH_hwQ', $searchString);
   my $content = get($url);
   die "Couldn't get $url" unless defined $content;   

   my $json_result = $json->decode($content);

   unless($json_result->{responseData}{results}->[0]){
      printf "\t\tNot found!\n";
      return;
   }

   # If List, then display and let choose if user console
   my $reformat = sub {
         my $item = shift;
         my $title = _removeHtml($item->{titleNoFormatting} || $item->{title});
         $item->{title_clear} = $title;
         return $item;
   };

   if($console and  my $list = $json_result->{responseData}{results} and scalar @{$json_result->{responseData}{results}} > 1){
      my $c = 1;
      print "\tFound more as one Entry!\n\tPlease choose from List:\n";
      foreach my $item (@$list){
         $item = &$reformat($item);
         next unless($item->{title_clear} =~ /\_/sig);
         printf "\t\t%d. %s\n", $c++, $item->{title_clear};
      }
      return if($c == 1);
      printf "\t\tAnswer: ";
      my $answer = <STDIN>;
      chomp $answer;
      print "\n";
      return unless($answer);

      # User input text for special search
      if($answer =~ /[a-z]+/){
         return getMovieData($data, $answer);
      }

      return $list->[int($answer)-1];
   } else {
      # Found only one item, choose this
      # also in none console mode
      return &$reformat($list->[0])
         if(not exists $list->[1]);
   }
   return undef; # Nothing found
}

sub saveInformationInTarget {
   my $movieData  = shift or die "No Data in saveInformationInTarget!";
   my $fileData    = shift or die "No FileData in saveInformationInTarget!";
   my $targetDir  = shift or die "No TargetDir in saveInformationInTarget!";

   my $path = sprintf('%s/%s', $targetDir, $movieData->{title_clear});

   unless($test){
      my $erg = `mkdir -p $path && mv $fileData->{file} $path/.`;
      printf "\t\tFile %s moved to %s!\n", 
         $fileData->{filename},
         $path;
   } else {
      print "\t\tTESTMODUS!!!\n";
      printf "\t\tFile %s moved to %s!\n", 
         $fileData->{filename},
         $path;

   }

   return 1;
}

sub _removeHtml {
   my $text = shift or die "No Text!";
   $text =~ s/\<.+?\>//sig;
   $text =~ s/(HD-Area.org\:|HD-Area.org)//sig;
   $text =~ s/\./_/sig;
   $text =~ s/_+/_/sig;
   $text =~ s/^[\s|_]+//sig;
   $text =~ s/[\s|_|-]+$//sig;
   return $text;
}

exit;
